package com.engine.annual.cmd;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import org.apache.commons.lang.math.NumberUtils;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.hrm.User;

import java.util.HashMap;
import java.util.Map;

public class AnnualAddAndUpdCmd extends AbstractCommonCommand<Map<String, Object>> {

    public AnnualAddAndUpdCmd(User user, Map<String, Object> params) {
        this.user = user;
        this.params = params;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        HashMap<String, Object> resultMap = new HashMap<>();
        RecordSet recordSet = new RecordSet();

        try {
            String querySql = "select * from t_annual where ID=" + params.get("id");
            boolean flag = recordSet.execute(querySql);

            String year = (String) params.get("year");
            if (StringUtil.isNotNull(year) || !year.matches("/^(19|20)\\d{2}$/")) {
                resultMap.put("api_msg", "年份不合法!");
                return resultMap;
            }

            String availabledays = (String) params.get("availabledays");
            String useddays = (String) params.get("useddays");
            if (!NumberUtils.isNumber(availabledays) || !NumberUtils.isNumber(useddays)) {
                resultMap.put("api_msg", "年假天数应为数字!");
                return resultMap;
            }

            if (Double.parseDouble(availabledays) < 0 || Double.parseDouble(useddays) < 0) {
                resultMap.put("api_msg", "年假天数应大于0!");
                return resultMap;
            }

            if (Double.parseDouble(availabledays) < Double.parseDouble(useddays)) {
                resultMap.put("api_msg", "已用年假天数不能大于可用年假天数！");
                return resultMap;
            }

            if (flag) {
                //修改
                String updSql = "update t_annual set YEAR=" + year + ",AVAILABLEDAYS=" + availabledays + ",USEDDAYS=" + useddays +
                        "where ID=" + params.get("id");
                recordSet.execute(updSql);

            } else {
                //添加
                String addSql = "insert into t_annual values (null,?,?,?,?)";
                recordSet.executeUpdate(addSql, params.get("hrmid"), year, availabledays, useddays);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("api_msg", "添加或修改失败！！！");
        }


        return resultMap;
    }
}
